<script setup lang="ts">

import MaForm from "@cps/ma-crud/components/form.vue";
import {computed, nextTick, provide, ref, watch, reactive, inject} from "vue";
import {Message} from '@arco-design/web-vue'
import dictHelp from "@/utils/dicthelp.js";
import ruleEvent from "@/api/logistics/ruleEvent.js";
import dicthelpApi from "@/api/dicthelpApi";

const crudRef = inject('crudRef')
const record = ref({})
const useAddForm = () => {
// 按照惯例，组合式函数名以“use”开头
  const defaultConfig = ref({
    width: 100,
    isFull: false,
    title: "",
    columns: [],
    infoColumns: [],
    infoData: {},
    visible: false,
    options: {},
    submit: () => {
      console.log("submit")
    },
  })
  const config = ref({})
  const data = ref({})
  const api = ref()
  const title = ref()
  const addFormConfig = ref({})
  addFormConfig.value.config = computed(() => {
    return {
      ...defaultConfig.value,
      ...config.value,
    }
  })
  addFormConfig.value.setData = (v) => {
    data.value = v
    return addFormConfig
  }
  addFormConfig.value.setConfig = (v) => {
    config.value = v
    return addFormConfig
  }
  addFormConfig.value.setApi = (v) => {
    api.value = v
    return addFormConfig
  }
  addFormConfig.value.open = async (formRef, data, userConfig = {}) => {
    await nextTick();
    if (userConfig) {
      config.value = userConfig
    }
    if (data) {
      record_id.value = data.id
      feeData.value = data.fee
      formRef.value.edit(data)
    } else {
      formRef.value.add()
    }
    return addFormConfig
  }
  // 通过返回值暴露所管理的状态
  return {addFormConfig, config}
}
const {addFormConfig} = useAddForm()
const addFormRef = ref()
const config = ref({})
const successCall = () => {
  crudRef.value.refresh()
}
const serviceOptions = ref([])

const templateColumns = ref([
  {
    title: "服务",
    dataIndex: "service_id",
    formType: "cascader",
    virtualListProps: {},
    // commonRules: {required: true, message: "请选择服务"},
    multiple: true,
    tree:serviceOptions,
  },
  {
    title: "名称",
    dataIndex: "name",
    commonRules: {required: true, message: "请填写名称"},
    formType: "input",
  },
  {
    title: "优先级",
    dataIndex: "level",
    commonRules: {required: true, message: "请填写名称"},
    formType: "input",
  },
  {
    title: "状态",
    dataIndex: "status",
    addDefaultValue: 1,
    dict: {
      data: [{label: '启用', value: 1}, {label: '禁用', value: 0}],
    },
    formType: "radio",
  },
  {
    title: "是否忽略其他规则",
    dataIndex: "ignore",
    addDefaultValue: 0,
    dict: {
      data: [{label: '是', value: 1}, {label: '否', value: 0}],
    },
    formType: "radio",
  },
  {
    title: "条件",
    dataIndex: "where_type",
    addDefaultValue: 1,
    dict: {
      name: 'EventWhere',
      translation: true,
    },
    formType: "radio",
    type: 'button',
  },
  {
    title: "货站",
    dataIndex: "Depots",
    formType: "select",
    multiple: true,
    dict: dictHelp.depot,
    hide: true,
  },
  {
    title: "国家",
    dataIndex: "Countrys",
    dict: {
      name: 'countrys',
      translation: true,
    },
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "用户等级",
    dataIndex: "CustomerGrade",
    formType: "select",
    dict: {
      url: 'customers/customerGrade/list',
      props: {label: 'name', value: 'id'},
      params: {
        select: 'id,name'
      },
      translation: true,
    },
    multiple: true,
    hide: true,
  },
  {
    title: "标识",
    dataIndex: "Label",
    formType: "select",
    dict: {
      url: 'logistics/tag/list',
      props: {label: 'name', value: 'id'},
      params: {
        select: 'id,name'
      },
      translation: true,
    },
    multiple: true,
    hide: true,
  },
  {
    title: "计费时间范围",
    dataIndex: "billingTime",
    formType: "range",
    showTime: true,
    settingHide: true,
    hide: true,
  },
  {
    title: "最小值",
    // hideLabel:true,
    dataIndex: "min_ActualWeight",
    formType: "input",
    settingHide: true,
    hide: true,
  },
  {
    title: "最大值",
    dataIndex: "max_ActualWeight",
    formType: "input",
    settingHide: true,
    hideLabel: true,
    hide: true,
  },
  {
    title: "最小值",
    // hideLabel:true,
    dataIndex: "min_ChargeWeight",
    formType: "input",
    settingHide: true,
    hide: true,
  },
  {
    title: "最大值",
    dataIndex: "max_ChargeWeight",
    formType: "input",
    settingHide: true,
    hideLabel: true,
    hide: true,
  },
  {
    title: "最小值",
    dataIndex: "min_ClientWeight",
    formType: "input",
    settingHide: true,
    hide: true,
  },
  {
    title: "最大值",
    dataIndex: "max_ClientWeight",
    formType: "input",
    settingHide: true,
    hideLabel: true,
    hide: true,
  },
  {
    title: "最小值",
    dataIndex: "min_ParcelCount",
    formType: "input",
    settingHide: true,
    hide: true,
  },
  {
    title: "最大值",
    dataIndex: "max_ParcelCount",
    formType: "input",
    settingHide: true,
    hideLabel: true,
    hide: true,
  },
  {
    title: "末端派送方式",
    dataIndex: "EndDeliveryType",
    dict: {
      name: 'endDeliveryType',
      translation: true,
    },
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "私人地址",
    dataIndex: "Personal",
    dict: {
      data: [
        {label: '是', value: 1},
      ],
      translation: true,
    },
    formType: "select",
    hide: true,
  },
  {
    title: "地址库",
    dataIndex: "Address",
    formType: "select",
    dict: {
      url: 'logistics/addressLibDetail/list',
      props: {label: 'code', value: 'id'},
      params: {
        select: 'id,code'
      },
      translation: true,
    },
    hide: true,
    multiple: true,
  },
  {
    title: "报关方式",
    dataIndex: "Exportwith",
    dict: {
      name: 'Exportwith',
      translation: true,
    },
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "清关方式",
    dataIndex: "Importwith",
    dict: {
      name: 'Importwith',
      translation: true,
    },
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "交税方式",
    dataIndex: "Taxwiths",
    dict: {
      name: 'TaxWith',
      translation: true,
    },
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "交货条款",
    dataIndex: "Deliverywith",
    dict: {
      name: 'DeliveryWith',
      translation: true,
    },
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "属性",
    dataIndex: "Attrs",
    dict: {
      name: 'ShipmentAttrs',
      translation: true,
    },
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "实际收货区域",
    dataIndex: "GetArea",
    dict: dictHelp.area,
    formType: "select",
    hide: true,
  },
  {
    title: "应该收货区域",
    dataIndex: "ShouldArea",
    dict: dictHelp.area,
    formType: "select",
    multiple: true,
    hide: true,
  },
  {
    title: "计费方式",
    dataIndex: "chargemode",
    dict: {
      name: 'ChargeMode',
      translation: true,
    },
    formType: "select",
    hide: true,
  },
  {
    title: "计重方式",
    dataIndex: "weightmode",
    dict: {
      name: 'WeightMode',
      translation: true,
    },
    formType: "select",
    hide: true,
  },
  {
    title: "尺寸必填",
    dataIndex: "size",
    dict: {
      data: [{label: '是', value: 1}, {label: '否', value: 0}],
    },
    formType: "select",
    hide: true,
  },
  {
    title: "电话必填",
    dataIndex: "phone",
    dict: {
      data: [{label: '是', value: 1}, {label: '否', value: 0}],
    },
    formType: "select",
    hide: true,
  },
  {
    title: "邮箱必填",
    dataIndex: "email",
    dict: {
      data: [{label: '是', value: 1}, {label: '否', value: 0}],
    },
    formType: "select",
    hide: true,
  },
  {
    title: "计泡系数",
    dataIndex: "volume_weight_radix",
    formType: "input",
    hide: true,
  },
  {
    title: "票计重精度",
    dataIndex: "shipment_step_weight",
    formType: "input",
    hide: true,
  },
  {
    title: "箱计重精度",
    dataIndex: "parcel_step_weight",
    formType: "input",
    hide: true,
  },
  {
    title: "最低箱实重",
    dataIndex: "min_parcel_actual_weight",
    formType: "input",
    hide: true,
  },
  {
    title: "最低箱材重",
    dataIndex: "min_parcel_volume_weight",
    formType: "input",
    hide: true,
  },
  {
    title: "最低箱收费重",
    dataIndex: "min_parcel_chargeable_weight",
    formType: "input",
    hide: true,
  },
  {
    title: "最大箱收费重",
    dataIndex: "max_parcel_chargeable_weight_required",
    formType: "input",
    hide: true,
  },
  {
    title: "最小票实重",
    dataIndex: "min_shipment_actual_weight_required",
    formType: "input",
    hide: true,
  },
  {
    title: "最大票实重",
    dataIndex: "max_shipment_actual_weight_required",
    formType: "input",
    hide: true,
  },
  {
    title: "最低票收费重",
    dataIndex: "min_shipment_chargeable_weight",
    formType: "input",
    hide: true,
  },
  {
    title: "最大票收费重",
    dataIndex: "max_shipment_chargeable_weight_required",
    formType: "input",
    hide: true,
  },
  {
    title: "费用类型",
    dataIndex: "fee_type",
    formType: "select",
    dict: {
      url: 'finance/feeType/list',
      props: {label: 'fee_name', value: 'id'},
      params: {
        select: 'id,fee_name'
      },
      translation: true,
    },
    hide: true,
  },
  {
    title: "",
    dataIndex: "fee_check",
    formType: "checkbox",
    dict: {
      data: [{label: '应收', value: "1"}, {label: '应付', value: "2"}, {label: '销售成本', value: "3"}],
      translation: true,
    },
    hide: true,
  },
  {
    title: "金额",
    dataIndex: "money",
    formType: "input",
    hide: true,
  },
  {
    title: "币种",
    dataIndex: "money_type",
    dict: {
      name: 'currencyType',
      translation: true,
    },
    formType: "select",
    hide: true,
  },
  {
    title: "单位",
    dataIndex: "fee_charge_type",
    dict: {
      name: 'ChargeType',
      translation: true,
    },
    formType: "select",
    hide: true,
  },
  {
    title: "添加费用",
    dataIndex: "button",
    formType: "button",
    type: 'primary',
    hide: true,
    onClick: (form) => {
      addFeeData(form.formModel.value)
    }
  },
  {
    dataIndex: "fee_list",
  },
]);
const options = ref({
  formOption: {
    viewType: 'drawer',
    width: '80%',
    layout: [
      {
        formType: 'grid-tailwind',
        colNumber: 1,
        cols: [
          {
            formList: [
              {dataIndex: "service_id"},
              {dataIndex: "name"},
              {dataIndex: "level"},
              {dataIndex: "status"},
              {dataIndex: "ignore"},
              {dataIndex: "where_type"},
            ]
          }
        ]
      },
      {
        formType: 'card',
        bordered: false,
        title: '逻辑',
        size: 'small',
        formList: [
          {
            formType: 'grid-tailwind',
            colNumber: 2,
            cols: [
              {
                formList: [
                  {dataIndex: "Depots"},
                  {dataIndex: "Countrys"},
                  {dataIndex: "Exportwith"},
                  {dataIndex: "Importwith"},
                  {dataIndex: "Taxwiths"},
                  {dataIndex: "Deliverywith"},
                  {dataIndex: "Attrs"},
                  {dataIndex: "GetArea"},
                  {dataIndex: "ShouldArea"},
                ]
              },
              {
                formList: [
                  {dataIndex: "EndDeliveryType"},
                  {dataIndex: "Personal"},
                  {dataIndex: "Address"},
                  {dataIndex: "CustomerGrade"},
                  {dataIndex: "Label"},
                  {dataIndex: 'billingTime'},
                  {
                    formType: 'group',
                    bordered: false,
                    customClass: ['form-inline-card'],
                    size: 'small',
                    title: '实重',
                    formList: [
                      {dataIndex: 'min_ActualWeight', title: '最小值'},
                      {dataIndex: 'max_ActualWeight', title: '最大值'},
                    ]
                  },
                  {
                    formType: 'group',
                    bordered: false,
                    customClass: ['form-inline-card'],
                    size: 'small',
                    title: '收费重',
                    formList: [
                      {dataIndex: 'min_ChargeWeight'},
                      {dataIndex: 'max_ChargeWeight'},
                    ]
                  },
                  {
                    formType: 'group',
                    bordered: false,
                    customClass: ['form-inline-card'],
                    size: 'small',
                    title: '客户重量',
                    formList: [
                      {dataIndex: 'min_ClientWeight'},
                      {dataIndex: 'max_ClientWeight'},
                    ]
                  },
                  {
                    formType: 'group',
                    bordered: false,
                    customClass: ['form-inline-card'],
                    size: 'small',
                    title: '箱数',
                    formList: [
                      {dataIndex: 'min_ParcelCount'},
                      {dataIndex: 'max_ParcelCount'},
                    ]
                  },
                  {
                    formType: 'group',
                    bordered: false,
                    customClass: ['form-inline-card'],
                    size: 'small',
                    title: '泡比',
                    formList: [
                      {dataIndex: 'min_WxRate'},
                      {dataIndex: 'max_WxRate'},
                    ]
                  },
                ]
              }
            ]
          },
        ]
      },
      {
        formType: 'grid-tailwind',
        customClass: ['form-inline-card-fee'],
        colNumber: 3,
        cols: [
          {
            formList: [
              {
                formType: 'card',
                bordered: false,
                title: '创建',
                size: 'small',
                formList: [
                  {dataIndex: 'size'},
                  {dataIndex: 'phone'},
                  {dataIndex: 'email'},
                ]
              }
            ]
          },
          {
            formList: [
              {
                formType: 'card',
                bordered: false,
                title: '拣货',
                size: 'small',
                formList: [
                  {dataIndex: 'chargemode'},
                  {dataIndex: 'weightmode'},
                  {dataIndex: 'volume_weight_radix'},
                  {dataIndex: 'shipment_step_weight'},
                  {dataIndex: 'parcel_step_weight'},
                  {dataIndex: 'min_parcel_actual_weight'},
                  {dataIndex: 'min_parcel_volume_weight'},
                  {dataIndex: 'min_parcel_chargeable_weight'},
                  {dataIndex: 'max_parcel_chargeable_weight_required'},
                  {dataIndex: 'min_shipment_actual_weight_required'},
                  {dataIndex: 'max_shipment_actual_weight_required'},
                  {dataIndex: 'min_shipment_chargeable_weight'},
                  {dataIndex: 'max_shipment_chargeable_weight_required'},
                ]
              }
            ]
          },
          {
            formList: [
              {
                formType: 'card',
                bordered: false,
                title: '费用',
                size: 'small',
                formList: [
                  {dataIndex: 'fee_type'},
                  {dataIndex: 'fee_check'},
                  {dataIndex: 'money'},
                  {dataIndex: 'money_type'},
                  {dataIndex: 'fee_charge_type'},
                  {dataIndex: 'button'},
                  {dataIndex: 'fee_list'},
                ]
              },

            ]
          }
        ]
      },
    ]
  },
  add: {
    title: '新增',
    api: ruleEvent.save
  },
  edit: {
    title: '编辑',
    api: ruleEvent.update
  },
  beforeEdit: (form) => {
    form.fee = feeData.value
    form.id = record_id.value
    return form
  },
  beforeAdd: (form) => {
    form.fee = feeData.value
    return form
  },
});
const record_id = ref(0)
const open = async (info) => {
  let serviceGroup = await dicthelpApi.serviceGroup()
  serviceOptions.value = serviceGroup.data
  if (info) {
    let res = await ruleEvent.read(info.id)
    info = res.data
  }
  feeData.value = []
  addFormConfig.value.open(addFormRef, info)
}

const getDictData = (key, value, crudRef) => {
  if (crudRef == undefined) {
    return;
  }
  let label = ''
  let dict = crudRef.getColumnService().dicts[key];
  if (dict !== undefined && dict.length > 0) {
    dict.map(i => {
      if (value && (typeof value) == 'object') {
        for (let index = 0; index < value.length; index++) {
          if (value[index] == i.value) {
            label += i.label + ' '
          }
        }
      } else {
        if (value == i.value) {
          label = i.label
        }
      }
    })
  }
  return label
}
const feeCount = ref(0)
const addFeeData = (data) => {
  if (!data.fee_type) {
    Message.error('请选择费用类型')
    return;
  }

  if (data.fee_check.length == 0) {
    Message.error('请选择应用类型')
    return;
  }
  if (!data.money) {
    Message.error('请填写金额')
    return;
  }
  if (!data.fee_charge_type) {
    Message.error('请选择单位')
    return;
  }
  if (!data.money_type) {
    Message.error('请选择币种')
    return;
  }

  feeData.value.push(
      {
        fee_type: data.fee_type,
        site: data.fee_check,
        money: data.money,
        unit_type: data.fee_charge_type,
        money_type: data.money_type,
        id: ++feeCount.value,
      }
  )
}
const delFeeData = (data) => {
  let index = feeData.value.findIndex(item => item.id === data.id);
  if (index !== -1) {
    feeData.value.splice(index, 1);
  }
}
const feeData = ref([])

provide('options', options.value)
provide('columns', templateColumns)
defineExpose({
  open,
  config
})
</script>

<template>
  <MaForm v-bind="config" ref="addFormRef" @success="successCall">
    <template #form-fee_list>
      <a-table :data="feeData" :pagination="false" class="fee-table">
        <template #columns>
          <a-table-column title="费用类型" field="fee_type">
            <template #cell="{ record }">
              {{ getDictData('fee_type', record.fee_type, crudRef) }}({{ getDictData('fee_check', record.site, crudRef) }})
            </template>
          </a-table-column>
          <a-table-column title="金额" field="money">
            <template #cell="{ record }">
              {{ record.money }}
            </template>
          </a-table-column>
          <a-table-column title="单位" field="fee_charge_type">
            <template #cell="{ record }">
              {{ getDictData('fee_charge_type', record.unit_type, crudRef) }}
            </template>
          </a-table-column>

          <a-table-column title="币种" field="money_type">
            <template #cell="{ record }">
              {{ getDictData('money_type', record.money_type, crudRef) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" field="money_type">
            <template #cell="{ record }">
              <a-link @click="delFeeData(record)">删除</a-link>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </template>
  </MaForm>

</template>

<style>
.form-inline-card > .arco-card-body {
  padding: 0;
  display: grid;
  grid: 1fr / 1fr 1fr;
  height: 50px;
}

.form-inline-card > .arco-card-header {
  display: none;
}

.form-inline-card-fee button {
  margin-bottom: 15px;
  float: right;
}

#fee_list .arco-form-item-content-flex {
  display: block
}
</style>